package com.appspot.eusms;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.android.vending.billing.util.IabHelper;
import com.appspot.eusms.crypto.MasterSecretUtil;
import com.appspot.eusms.database.DatabaseFactory;
import com.appspot.eusms.recipients.RecipientFactory;
import com.appspot.eusms.recipients.RecipientFormattingException;
import com.appspot.eusms.recipients.Recipients;
import com.appspot.eusms.service.ApplicationMigrationService;
import com.appspot.eusms.util.TextSecurePreferences;

import org.whispersystems.textsecure.crypto.MasterSecret;

public class RoutingActivity extends PassphraseRequiredSherlockActivity {

    private static final int STATE_CREATE_PASSPHRASE = 1;
    private static final int STATE_PROMPT_PASSPHRASE = 2;
    private static final int STATE_IMPORT_DATABASE = 3;
    private static final int STATE_CONVERSATION_OR_LIST = 4;
    private static final int STATE_UPGRADE_DATABASE = 5;
    private static final int STATE_PROMPT_PUSH_REGISTRATION = 6;

    private MasterSecret masterSecret = null;
    private boolean isVisible = false;
    private boolean canceledResult = false;
    private boolean newIntent = false;

    private String String1 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt+siKEFDzEHIm7mmRTVseuqy/bIXVu8HHrkAPrIRSAkC5qBOKxf72XAQt69U/uT0H4UKlq9dkFBTVv";
    private String String2 = "DVgPZl6UOJfUH+X2Fm9IRG9BI8p1nDTEngb8NQt9d7z3lEPpMK0F1vbPQBBZfzhi8fNWTjtNmkUMhWZ201H4zeMK2GlJq8oOwA0QtLhpoRWc3Ta1OoE806Lt3m";
    private String String3 = "E/z8ZSegbcK/p4UpL4mv2iQlzOqpcVEYBcnx9I/fjdKnfdBmswxXsueJRBaKhNeRp7/fRy0fMdFCQ+CAQSxOe5RuJFtaz/adzJDiDQicYFAqIMjs3ZLsMVsf7p";
    private String String4 = "v5+urxkoSqBD6zakYUEwIDAQAB";

    private IabHelper mHelper;
    // Debug tag, for logging
    private static final String TAG = "EUSMS";

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        this.newIntent = true;
    }

    @Override
    public void onResume() {
        if (this.canceledResult && !this.newIntent) {
            finish();
        }

        this.newIntent = false;
        this.canceledResult = false;
        this.isVisible = true;
        super.onResume();
    }

    @Override
    public void onPause() {
        this.isVisible = false;
        super.onPause();
    }

    @Override
    public void onNewMasterSecret(MasterSecret masterSecret) {
        this.masterSecret = masterSecret;

        if (isVisible) {
            routeApplicationState();
        }
    }

    @Override
    public void onMasterSecretCleared() {
        this.masterSecret = null;

        if (isVisible) {
            routeApplicationState();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
            canceledResult = true;
        }
    }

    private void routeApplicationState() {
        int state = getApplicationState();

        switch (state) {
            case STATE_CREATE_PASSPHRASE:
                handleCreatePassphrase();
                break;
            case STATE_PROMPT_PASSPHRASE:
                handlePromptPassphrase();
                break;
            case STATE_IMPORT_DATABASE:
                handleImportDatabase();
                break;
            case STATE_CONVERSATION_OR_LIST:
                handleDisplayConversationOrList();
                break;
            case STATE_UPGRADE_DATABASE:
                handleUpgradeDatabase();
                break;
            case STATE_PROMPT_PUSH_REGISTRATION:
                handlePushRegistration();
                break;
        }
    }

    private void handleCreatePassphrase() {
        Intent intent = new Intent(this, PassphraseCreateActivity.class);
        startActivityForResult(intent, 1);
    }

    private void handlePromptPassphrase() {
//      mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
//          public void onIabSetupFinished(IabResult result) {
//              if (!result.isSuccess()) {
//                  // Oh noes, there was a problem.
//                  Log.d(TAG, "EUSMS - Problem setting up In-app Billing: " + result);
//              }
//              // Hooray, IAB is fully set up!
//
//          }
//      });
        Intent intent = new Intent(this, PassphrasePromptActivity.class);
        startActivityForResult(intent, 2);
    }

    private void handleImportDatabase() {
        Intent intent = new Intent(this, DatabaseMigrationActivity.class);
        intent.putExtra("master_secret", masterSecret);
        intent.putExtra("next_intent", getPushRegistrationIntent());

        startActivity(intent);
        finish();
    }

    private void handleUpgradeDatabase() {
        Intent intent = new Intent(this, DatabaseUpgradeActivity.class);
        intent.putExtra("master_secret", masterSecret);
        intent.putExtra("next_intent", TextSecurePreferences.hasPromptedPushRegistration(this) ?
                getConversationListIntent() : getPushRegistrationIntent());

        startActivity(intent);
        finish();
    }

    private void handlePushRegistration() {
        Intent intent = getPushRegistrationIntent();
        intent.putExtra("next_intent", getConversationListIntent());
        startActivity(intent);
        finish();
    }

    private void handleDisplayConversationOrList() {
        final ConversationParameters parameters = getConversationParameters();

        final Intent intent;
        if (isShareAction()) {
            intent = getShareIntent(parameters);
        } else if (parameters.recipients != null) {
            intent = getConversationIntent(parameters);
        } else {
            intent = getConversationListIntent();
        }
        startActivity(intent);
        finish();
    }

    private Intent getConversationIntent(ConversationParameters parameters) {
        Intent intent = new Intent(this, ConversationActivity.class);
        intent.putExtra(ConversationActivity.RECIPIENTS_EXTRA, parameters.recipients != null ? parameters.recipients.toIdString() : "");
        intent.putExtra(ConversationActivity.THREAD_ID_EXTRA, parameters.thread);
        intent.putExtra(ConversationActivity.MASTER_SECRET_EXTRA, masterSecret);
        intent.putExtra(ConversationActivity.DRAFT_TEXT_EXTRA, parameters.draftText);
        intent.putExtra(ConversationActivity.DRAFT_IMAGE_EXTRA, parameters.draftImage);
        intent.putExtra(ConversationActivity.DRAFT_AUDIO_EXTRA, parameters.draftAudio);
        intent.putExtra(ConversationActivity.DRAFT_VIDEO_EXTRA, parameters.draftVideo);

        return intent;
    }

    private Intent getShareIntent(ConversationParameters parameters) {
        Intent intent = new Intent(this, ShareActivity.class);
        intent.putExtra("master_secret", masterSecret);

        if (parameters != null) {
            intent.putExtra(ConversationActivity.DRAFT_TEXT_EXTRA, parameters.draftText);
            intent.putExtra(ConversationActivity.DRAFT_IMAGE_EXTRA, parameters.draftImage);
            intent.putExtra(ConversationActivity.DRAFT_AUDIO_EXTRA, parameters.draftAudio);
            intent.putExtra(ConversationActivity.DRAFT_VIDEO_EXTRA, parameters.draftVideo);
        }

        return intent;
    }

    private Intent getConversationListIntent() {
        Intent intent = new Intent(this, ConversationListActivity.class);
        intent.putExtra("master_secret", masterSecret);

        return intent;
    }

    private Intent getPushRegistrationIntent() {
        Intent intent = new Intent(this, RegistrationActivity.class);
        intent.putExtra("master_secret", masterSecret);

        return intent;
    }

    private int getApplicationState() {
        if (!MasterSecretUtil.isPassphraseInitialized(this))
            return STATE_CREATE_PASSPHRASE;

        if (masterSecret == null)
            return STATE_PROMPT_PASSPHRASE;

        if (!ApplicationMigrationService.isDatabaseImported(this))
            return STATE_IMPORT_DATABASE;

        if (DatabaseUpgradeActivity.isUpdate(this))
            return STATE_UPGRADE_DATABASE;

        if (!TextSecurePreferences.hasPromptedPushRegistration(this))
            return STATE_PROMPT_PUSH_REGISTRATION;

        return STATE_CONVERSATION_OR_LIST;
    }

    private ConversationParameters getConversationParameters() {
        if (isSendAction()) {
            return getConversationParametersForSendAction();
        } else if (isShareAction()) {
            return getConversationParametersForShareAction();
        } else {
            return getConversationParametersForInternalAction();
        }
    }

    private ConversationParameters getConversationParametersForSendAction() {
        Recipients recipients;
        long threadId = getIntent().getLongExtra("thread_id", -1);

        try {
            String data = getIntent().getData().getSchemeSpecificPart();
            recipients = RecipientFactory.getRecipientsFromString(this, data, false);
            threadId = DatabaseFactory.getThreadDatabase(this).getThreadIdIfExistsFor(recipients);
        } catch (RecipientFormattingException rfe) {
            recipients = null;
        }

        return new ConversationParameters(threadId, recipients, null, null, null, null);
    }

    private ConversationParameters getConversationParametersForShareAction() {
        String type = getIntent().getType();
        String draftText = null;
        Uri draftImage = null;
        Uri draftAudio = null;
        Uri draftVideo = null;

        if ("text/plain".equals(type)) {
            draftText = getIntent().getStringExtra(Intent.EXTRA_TEXT);
        } else if (type != null && type.startsWith("image/")) {
            draftImage = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
        } else if (type != null && type.startsWith("audio/")) {
            draftAudio = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
        } else if (type != null && type.startsWith("video/")) {
            draftVideo = getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
        }

        return new ConversationParameters(-1, null, draftText, draftImage, draftAudio, draftVideo);
    }

    private ConversationParameters getConversationParametersForInternalAction() {
        long threadId = getIntent().getLongExtra("thread_id", -1);
        Recipients recipients = getIntent().getParcelableExtra("recipients");

        return new ConversationParameters(threadId, recipients, null, null, null, null);
    }

    private boolean isShareAction() {
        return Intent.ACTION_SEND.equals(getIntent().getAction());
    }

    private boolean isSendAction() {
        return Intent.ACTION_SENDTO.equals(getIntent().getAction());
    }

    private static class ConversationParameters {
        public final long thread;
        public final Recipients recipients;
        public final String draftText;
        public final Uri draftImage;
        public final Uri draftAudio;
        public final Uri draftVideo;

        public ConversationParameters(long thread, Recipients recipients,
                                      String draftText, Uri draftImage, Uri draftAudio, Uri draftVideo) {
            this.thread = thread;
            this.recipients = recipients;
            this.draftText = draftText;
            this.draftImage = draftImage;
            this.draftAudio = draftAudio;
            this.draftVideo = draftVideo;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        String base64EncodedPublicKey = String1+String2+String3+String4;
//
//        // Create the helper, passing it our context and the public key to verify signatures with
//        Log.d(TAG, "EUSMS: Creating IAB helper.");
//        mHelper = new IabHelper(this, base64EncodedPublicKey);
//
//        // enable debug logging (for a production application, you should set this to false).
//        mHelper.enableDebugLogging(true);
//
//        // Start setup. This is asynchronous and the specified listener
//        // will be called once setup completes.
//        Log.d(TAG, "EUSMS: IAB - Starting setup.");
//        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
//            public void onIabSetupFinished(IabResult result) {
//                Log.d(TAG, "EUSMS: IAB - Setup finished.");
//
//                if (!result.isSuccess()) {
//                    // Oh noes, there was a problem.
//                    complain("Problem setting up in-app billing: " + result);
//                    return;
//                }
//
//                // Have we been disposed of in the meantime? If so, quit.
//                if (mHelper == null) return;
//
//            }
//        });
    }

    void complain(String message) {
        Log.e(TAG, "**** EUSMS Error: " + message);
        alert("Error: " + message);
    }

    void alert(String message) {
        AlertDialog.Builder bld = new AlertDialog.Builder(this);
        bld.setMessage(message);
        bld.setNeutralButton("OK", null);
        Log.d(TAG, "EUSMS - Showing alert dialog: " + message);
        bld.create().show();
    }

    //We're being destroyed. It's important to dispose of the helper here!
    @Override
    public void onDestroy() {
        super.onDestroy();

//        // very important:
//        Log.d(TAG, "Destroying helper.");
//        if (mHelper != null) {
//            mHelper.dispose();
//            mHelper = null;
//        }
    }

}
